package com.zhq.mvc;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * @Author:钟豪强
 * @Description:    处理请求的Servlet
 * @Date Created in  2020-08-${Day} 14:14
 * @Modified By:
 */
public class DispatcherServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        //找到配置文件的路径
        String path = config.getInitParameter("contentConfigLocation");
        //用类加载读取.properties配置文件,得到io流信息
        InputStream is = DispatcherServlet.class.getClassLoader().getResourceAsStream(path);
        HandlerMapping.load(is);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接收用户的uri
        String uri = req.getRequestURI();
        //取出对应的处理请求方法
        HandlerMapping.MVCMapping mapping = HandlerMapping.get(uri);
        System.out.println(mapping);
        if (mapping == null) {
            resp.sendError(404,"自定义MVC:映射地址不存在"+uri);
            return;
        }
        Object obj = mapping.getObj();
        Method method = mapping.getMethod();
        Object result = null;
        try {
            result = method.invoke(obj, req, resp);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        switch (mapping.getType()) {
            case TEXT:
                resp.getWriter().write((String) result);
                break;
            case VIEW:
                resp.sendRedirect((String) result);
                break;
        }
    }
}
